package com.heima.leetcode.datastructure.linkedlist;

import java.util.Iterator;

/**
 * leetcode很多题目用到的节点类，leetcode中没有提供外层的集合类，集合里面包括一堆节点
 */
public class ListNode {
    public int val; // 用pubic是想要节点可以直接.val用这些属性，是想要其他包也可以直接访问
    public ListNode next;

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder(64);
        builder.append("[");
        for (ListNode p = this; p != null; p = p.next){
            builder.append(p.val);
            if (p.next != null){
                builder.append(",");
            }
        }
        builder.append("]");
        return builder.toString();
    }

    public static ListNode of(int... elements){
        if (elements == null || elements.length == 0){
            return null;
        }
        ListNode head = new ListNode(elements[0], null);
        ListNode p = head;
        for (int i = 1; i < elements.length; i++, p = p.next) {
            p.next = new ListNode(elements[i],null);
        }
        return head;
    }
}
